package cn.spike.user.service.impl;

import cn.spike.basic.exception.BusinessException;
import cn.spike.basic.util.Md5Utils;
import cn.spike.basic.util.StrUtils;
import cn.spike.user.domain.Logininfo;
import cn.spike.user.domain.User;
import cn.spike.user.mapper.LogininfoMapper;
import cn.spike.user.mapper.UserMapper;
import cn.spike.user.service.IUserService;
import cn.spike.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 业务实现类：
 */
@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;


    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //校验
        //1.空值校验
        if(phone.isEmpty() || phoneCode.isEmpty() || password.isEmpty() || passwordRepeat.isEmpty()){
            throw new BusinessException("注册信息不能为空");
        }
        //2.两次密码是否一致校验
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        //3.短信验证码是否过期 - 短信验证码是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj == null){
            throw new BusinessException("短信验证码已过期,请重新获取");
        }
        if(!phoneCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("短信验证码错误");
        }

        //添加
        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        //先添加logininfo
        logininfoMapper.add(logininfo);
        //在添加user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

    }

    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //校验
        //1.空值校验
        if(email.isEmpty() || password.isEmpty() || passwordRepeat.isEmpty()){
            throw new BusinessException("注册信息不能为空");
        }
        String pattern = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        if(!(Pattern.matches(pattern,email))){
            throw new BusinessException("请输入正确邮箱地址");
        }
        //2.两次密码不一致判断
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        //3.判断邮箱是否已经注册
        if(userMapper.loadByEmail(email)!=null){
            throw new BusinessException("该邮箱已注册,如忘记密码,可联系管理员找回");
        }

        //添加到数据库
        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setDisable(false);
        //1.先添加logininfo
        logininfoMapper.add(logininfo);
        //2.再添加user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

        //发送激活邮件
        //发送复杂邮件的工具类
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true,"utf-8");
        helper.setFrom("794921047@qq.com");//设置发件人
        helper.setSubject("宠物之家用户注册激活邮件");//设置邮件主题
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>你的账号注册成功!!!</h1>"+
                "<a href='http://127.0.0.1:8080/user/active/"+logininfo.getId()+"'>点击该链接激活</a>",true);
        //设置收件人
        //helper.setTo(user.getEmail());
        helper.setTo("794921047@qq.com");
        //发送邮件
        javaMailSender.send(mimeMessage);
    }


    /**
     * 账号激活的业务
     * @param id
     */
    @Override
    public void activation(Long logininfoId) {
        logininfoMapper.activation(logininfoId);
    }

    /**
     * 将一个map转换成User对象的方法
     * @param map
     * @return
     */
    private User map2User(Map<String, String> map) {
        String phone = map.get("phone");
        String email = map.get("email");

        User user = new User();
        if(phone!=null){
            user.setUsername(phone);
            user.setPhone(phone);
        }else{
            user.setUsername(email);
            user.setEmail(email);
        }
        user.setState(1);
        //生成32位盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String md5 = Md5Utils.encrypByMd5(map.get("password")+salt);
        user.setPassword(md5);
        user.setSalt(salt);
        return user;
    }

    /**
     * 将user对象转换成logininfo对象的方法
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户类型 - 为1
        return logininfo;
    }

    /**
     * 重写添加方法 - 为了同步信息到logininfo中
     * @param user
     */
    @Override
    @Transactional
    public void add(User user) {
        String password = user.getPassword();
        //获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        password = Md5Utils.encrypByMd5(password + salt);
        user.setPassword(password);
        //将user对象转换为logininfo对象
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        //获取login info的自增id设置到user的logininfoId
        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }

    /**
     * 重写删除方法 - 同步到登录信息表中
     * @param id
     */
    @Override
    @Transactional
    public void delete(Long id) {
        User user = userMapper.loadById(id);
        logininfoMapper.delete(user.getLogininfoId());
        super.delete(id);
    }

    /**
     * 重写修改方法 - 同步到登陆信息中
     * @param user
     */
    @Override
    @Transactional
    public void update(User user) {//前端传过来的user是没有登陆信息id
        String oldPassword = user.getPassword();
        User oldUser = userMapper.loadById(user.getId());//loginfo_id
        //如果前端传过来的密码和数据库中保存的密码不一致说明用户更改了密码
        if(!oldPassword.equals(oldUser.getPassword())){
            //处理盐值和密码
            String salt = StrUtils.getComplexRandomString(32);
            String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
            user.setSalt(salt);
            user.setPassword(md5Pwd);
        }
        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.loadById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //如果用户的状态为0 - 需要同步到登录信息中 - 禁用
        if(user.getState()==0){
            oldLogininfo.setDisable(false);
        }else{
            oldLogininfo.setDisable(true);
        }
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }

    @Override
    public void patchDelete(List<Long> ids) {
        List<Long> LogininfoIds = userMapper.patchSelectLogininfoId(ids);
        logininfoMapper.patchDelete(LogininfoIds);
        super.patchDelete(ids);
    }
}
